package com.lihepeng.leecode.juc;

import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;

/**
 * 打印 0 奇数 和偶数
 * 使用信号量完成
 */
public class ZeroEvenOdd {
    private int n;
    private Semaphore odds = new Semaphore(1);
    private Semaphore even = new Semaphore(1);
    private Semaphore zero = new Semaphore(1);
    // 状态表示为 1表示 奇数 0 表示偶数
    public ZeroEvenOdd(int n) {
        this.n = n;
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for (int i=0;i<n;i++) {
            zero.acquire();
            printNumber.accept(0);
            if ((i&1)==1) {
                odds.release();
            }else {
                even.release();
            }
        }

    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for (int i=0;i<n;i++) {
            if (i/2==0) {
                even.acquire();
                printNumber.accept(i);
                zero.release();
            }

        }

    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for (int i=0;i<n;i++) {
            if (i/2!=0) {
                odds.acquire();
                printNumber.accept(i);
                zero.release();
            }

        }
    }
}
